package com.maliankeji.mybatisflexdemo.util;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Tools {

    //秘钥
    private final static String PKEY = "123456543789213A";

    private final static Logger LOGGER = LogManager.getLogger(Tools.class);

    public static String toJSON(Result result){
        //将结果转化成json字符串
        String json = JSON.toJSONString(result);

        //将json字符串转换成json对象
        JSONObject jsonObject = JSON.parseObject(json);

        //获取“data”对应的内容
        JSONArray dataObject = jsonObject.getJSONArray("data");

        //将“data”字段移除
        jsonObject.remove("data");

        //将“message”字段放到“data”前面
        //先临时保存“message”字段
        String message = jsonObject.getString("message");

        //再移除“message”字段然后放入json对象
        jsonObject.remove("message");
        jsonObject.put("message",message);

        //再将“data”字段放入json对象
        jsonObject.put("data", dataObject);

        return jsonObject.toJSONString();
    }

    public static String encryptStr(String str){
        LOGGER.info("字符串原文：{}", str);
        try {
            // 加密
            String key = HexUtil.encodeHexStr(PKEY);
            SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES,key.getBytes());
            return aes.encryptHex(str, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            LOGGER.error("字符串加密出错：{}",str);
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    public static String decryptStr(String encryptedStr, boolean isDataSource){
        String key = HexUtil.encodeHexStr(PKEY);
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES,key.getBytes());
        String decryptStr = aes.decryptStr(encryptedStr, CharsetUtil.CHARSET_UTF_8);
        if(!isDataSource)
            LOGGER.info("字符串解密:{}", decryptStr);
        return decryptStr;
    }

    public static String decryptStr(String encryptedStr){
        return decryptStr(encryptedStr, false);
    }
}
